import java.util.HashSet;
import java.util.Set;

class WordDictionary {

    TrieNode head;

    class TrieNode{
        TrieNode[] nodes;
        boolean isEnd;
        public TrieNode() {
            this.nodes = new TrieNode[26];
            isEnd = false;
        }
    }

    public WordDictionary() {
        head = new TrieNode();
    }

    private void travelInsert(TrieNode tmpNode, final String word, final int ind){
        int tmpLoc = word.charAt(ind) - 'a';
        if(tmpNode.nodes[tmpLoc] == null){
            tmpNode.nodes[tmpLoc] = new TrieNode();
        }
        if(ind == word.length() - 1){
            tmpNode.nodes[tmpLoc].isEnd = true;
            return;
        }
        travelInsert(tmpNode.nodes[tmpLoc], word, ind+1);
    }

    private boolean travelSearch(TrieNode tmpNode, final String word, final int ind){
        if (tmpNode == null){return false;}
        if(word.length() == ind){
            if(tmpNode.isEnd){
                return true;
            }
            return false;
        }
        char tmpC = word.charAt(ind);
        if(tmpC != '.'){
            int tmpLoc = tmpC - 'a';
            if(travelSearch(tmpNode.nodes[tmpLoc], word, ind+1)){
                return true;
            }
            return false;
        }
        for (int i = 0; i < 26; i++) {
            if(travelSearch(tmpNode.nodes[i], word, ind+1)){
                return true;
            }
        }
        return false;
    }

    public void addWord(String word) {
        travelInsert(head, word, 0);
    }

    public boolean search(String word) {
        return travelSearch(head, word, 0);
    }

    public static void main(String[] args) {
        WordDictionary wd = new WordDictionary();
//        wd.addWord("bad");
//        wd.addWord("pad");
//        wd.addWord("mad");
//        System.out.println(wd.search("pad"));
//        System.out.println(wd.search("psd"));
//        System.out.println(wd.search("bad"));
//        System.out.println(wd.search(".ad"));
//        System.out.println(wd.search("pad."));
//
//        System.out.println(wd.search(".pad"));
        wd.addWord("a");
        wd.addWord("ab");
        System.out.println(wd.search("a."));
    }
}
